package com.fingard.dsp.bank.directbank.fngrd01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class FnGrd01RealTime extends FnGrd01Base implements IRealTime {
    public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        if ("9108CNVRT".equals(p_req9108.reqHeader.commandCode)) {
            //单笔转批量
            ReqBatPayRec p_req1988 = new ReqBatPayRec(p_req9108);//单笔转批量
            FnGrd01BatPayRec tmpBatPay = new FnGrd01BatPayRec();
            tmpBatPay.setSbLog(this.sbLog);
            tmpBatPay.setLogFlushTime(this.logFlushTime);
            tmpBatPay.reqHeader = p_req9108.reqHeader.clone();
            tmpBatPay.reqHeader.isFromSinglePay = true;
            tmpBatPay.reqHeader.transType = "9188";
            tmpBatPay.reqHeader.commandCode = "918801";
            tmpBatPay.bankFront = this.bankFront;
            p_req1988.reqHeader = tmpBatPay.reqHeader;
            RetAtsBatPayRec retAts1988 = tmpBatPay.d_9188_BatPay(p_req1988);
            RetAtsSglDetail tmpRetDetail = retAts1988.convertToSingle();
            retAts.writeRetDetail(tmpRetDetail);
        } else {
            retAts = d_910801_RealTimeRec(p_req9108);
        }
        return retAts;
    }

    public RetAtsSingle d_910801_RealTimeRec(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
        FnGrd01Header bankHeader = new FnGrd01Header();
        boolean isCntr=false;
        if("9108Cntr".equals(p_req9108.reqHeader.commandCode)){
            bankHeader.CommandCode = "111G1";
            isCntr=true;
        }else{
            bankHeader.CommandCode = "11111";
        }

        bankHeader.CorpBankCode = getBankConfig().getMapValueByKey("corBankCodeMapping", p_req9108.singleDetail.recAct);
        if (StringHelper.isNullOrEmpty(bankHeader.CorpBankCode)) {
            WriteBankLogLn2("CorpBankCode为空，请配置corBankCodeMapping映射");
        }
        bankHeader.TransSeqID = getQryTransID();
        bankHeader.SourceChannel = "ATS01";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("RealTimeSingleTransReq");
        xmlWriter.writeElementString("MoneyWay", "2");
        xmlWriter.writeElementString("TransDate", p_req9108.singleDetail.payDate.replace("-", ""));
        XElement tmpXElement = new XElement("Trans", "");
        tmpXElement.addChild(new XElement("TransNo", p_req9108.singleDetail.askNumber));
        String agreementNo = "";
		String[] authCodeSp = p_req9108.singleDetail.authCode.split("__");
		String protocolCode = authCodeSp[0];
		if(authCodeSp.length>1){
			agreementNo = authCodeSp[1];
		}
        tmpXElement.addChild(new XElement("ProtocolCode", protocolCode));
        tmpXElement.addChild(new XElement("EnterpriseAccNum", p_req9108.singleDetail.recAct));
        tmpXElement.addChild(new XElement("CustBankCode", p_req9108.singleDetail.payBankCode));
        tmpXElement.addChild(new XElement("CustAccNum", p_req9108.singleDetail.payAct));
        tmpXElement.addChild(new XElement("CustAccName", p_req9108.singleDetail.payName));
        tmpXElement.addChild(new XElement("AreaCode", p_req9108.singleDetail.payArea));
        tmpXElement.addChild(new XElement("BankLocationCode", p_req9108.singleDetail.cnapsCode));
        tmpXElement.addChild(new XElement("BankLocationName", p_req9108.singleDetail.payBankLocation));
        //卡折标记0卡;1折
        if (p_req9108.singleDetail.cardType != null && p_req9108.singleDetail.cardType.equals("1")) {
            tmpXElement.addChild(new XElement("CardType", "1"));
        } else {
            tmpXElement.addChild(new XElement("CardType", "0"));
        }

        if (p_req9108.singleDetail.isPrivate.equals("1")) {//0：私人   1：公司
            tmpXElement.addChild(new XElement("IsPrivate", "0"));
        } else {
            tmpXElement.addChild(new XElement("IsPrivate", "1"));
        }
        if(isCntr){
            tmpXElement.addChild((new XElement("AgreementNo", agreementNo)));//* 代收协议编号 *//
            tmpXElement.addChild((new XElement("PolicyNumber", p_req9108.singleDetail.insuPolicyNum)));//保单号
            //PolicyNumber
        }
        tmpXElement.addChild(new XElement("IsUrgent", ""));
        tmpXElement.addChild(new XElement("Amount", p_req9108.singleDetail.payAmount));
        tmpXElement.addChild(new XElement("Currency", convertCurToBank(p_req9108.singleDetail.payCur)));
        tmpXElement.addChild(new XElement("CertType", convertCertTypeToBank(p_req9108.singleDetail.certType)));
        tmpXElement.addChild(new XElement("CertNum", p_req9108.singleDetail.certNum));
        tmpXElement.addChild(new XElement("ReconciliationCode", p_req9108.singleDetail.abstractATS));
        tmpXElement.addChild(new XElement("Mobile", ""));
        tmpXElement.addChild(new XElement("Purpose", p_req9108.singleDetail.purpose));
        tmpXElement.addChild(new XElement("Memo", p_req9108.singleDetail.memo));
        tmpXElement.addChild(new XElement("Extent1", ""));
        tmpXElement.addChild(new XElement("Extent2", ""));
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();

        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/RespCode");
                String tmpRetMsg = tmpBkReader.getFirstText("/Root/Head/RespInfo");
                int tmpIntRespCode = -1;
                if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                    tmpIntRespCode = Integer.parseInt(tmpRetCode);
                }
                tmpRetDetail.respCode = "0";
                if (tmpIntRespCode >= 0 || (tmpIntRespCode < 0 && "308".equals(bankHeader.CorpBankCode))) {
                    String transStatus = tmpBkReader.getFirstText("/Root/RealTimeSingleTransResp/Trans/State");
                    if ("4".equals(transStatus) && "308".equals(bankHeader.CorpBankCode) || tmpRetMsg.contains("处理中")) {
                        long realSleepTime = getBankConfig().getValueAsInt("realSleepTime");
                        Thread.sleep(realSleepTime * 1000);

                        //bankHeader = new FnGrd01Header();
                        bankHeader.CommandCode = "21111";
                        bankHeader.TransSeqID = getQryTransID();

                        xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                        writeCommonHeader(xmlWriter, bankHeader);
                        xmlWriter.writeStartElement("RealTimeSingleTransQueryReq");
                        xmlWriter.writeElementString("TransNo", p_req9108.singleDetail.askNumber);
                        xmlWriter.writeElementString("TransDate", Format.Date8Format.format(p_req9108.singleDetail.getPayDateTime()));
                        xmlWriter.writeEndDocument();

                        tmpStrRet = sendToBank(xmlWriter.toXmlString());

                        if (tmpStrRet[0].length() == 0) {
                            tmpSbMsg = new StringBuilder();
                            tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                tmpRetCode = tmpBkReader.getFirstText("/Root/Head/RespCode");
                                tmpRetMsg = tmpBkReader.getFirstText("/Root/Head/RespInfo");
                                if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                                    tmpIntRespCode = Integer.parseInt(tmpRetCode);
                                }
                                tmpRetDetail.respCode = "0";

                                if (tmpIntRespCode >= 0) {
                                    tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/TransNo");
                                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/Info");
                                    tmpRetDetail.transState = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/State");
                                    tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/InfoCode");
                                    tmpRetDetail.transAmt = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/Amount");
                                } else {
                                    tmpRetDetail.respCode = "-1";
                                    if (StringHelper.isNullOrEmpty(tmpRetMsg)) {
                                        tmpRetDetail.respInfo = "前置返回查询失败RespCode：" + tmpRetCode;
                                    } else {
                                        tmpRetDetail.respInfo = tmpRetMsg;
                                        if (tmpRetMsg.contains("处理中")) {
                                            tmpRetDetail.respCode = "0";
                                            tmpRetDetail.transState = "4";
                                            tmpRetDetail.payInfoCode = "I4001";
                                        }
                                    }
                                }
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = tmpSbMsg.toString();
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = tmpStrRet[1];
                        }
                    } else {
                        tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/Root/RealTimeSingleTransResp/Trans/TransNo");
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/RealTimeSingleTransResp/Trans/Info");
                        tmpRetDetail.transState = tmpBkReader.getFirstText("/Root/RealTimeSingleTransResp/Trans/State");
                        tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/Root/RealTimeSingleTransResp/Trans/InfoCode");
                        tmpRetDetail.transAmt = tmpBkReader.getFirstText("/Root/RealTimeSingleTransResp/Trans/Amount");
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    if (StringHelper.isNullOrEmpty(tmpRetMsg)) {
                        tmpRetDetail.respInfo = "前置返回查询失败RespCode：" + tmpRetCode;
                    } else {
                        tmpRetDetail.respInfo = tmpRetMsg;
                        if (tmpRetMsg.contains("处理中")) {
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.transState = "4";
                            tmpRetDetail.payInfoCode = "I4001";
                        }
                    }
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            tmpRetDetail.respCode = "0";
            tmpRetDetail.respInfo = tmpStrRet[1];
            tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
            tmpRetDetail.transState = PaymentState.FAIL_Payment;
            tmpRetDetail.payInfoCode = tmpStrRet[0];
        } else {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = tmpStrRet[1];
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    //9144 状态查询
    public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        tmpRetAtsDetail.reqSeqID = p_req9144.askNumber;

        try {
            FnGrd01Header bankHeader = new FnGrd01Header();
            if("9108Cntr".equals(p_req9144.reqHeader.commandCode)){
                bankHeader.CommandCode = "211G1";
            }else{
                bankHeader.CommandCode = "21111";
            }

            bankHeader.CorpBankCode = getBankConfig().getMapValueByKey("corBankCodeMapping", p_req9144.recAct);
            if (StringHelper.isNullOrEmpty(bankHeader.CorpBankCode)) {
                WriteBankLogLn2("CorpBankCode为空，请配置corBankCodeMapping映射");
            }

            bankHeader.TransSeqID = getQryTransID();
            bankHeader.SourceChannel = "ATS01";

            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("RealTimeSingleTransQueryReq");
            xmlWriter.writeElementString("TransNo", p_req9144.askNumber);
            xmlWriter.writeElementString("TransDate", Format.Date8Format.format(p_req9144.getBgnDateTime()));
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/RespCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/Root/Head/RespInfo");
                    int tmpIntRespCode = -1;
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        tmpIntRespCode = Integer.parseInt(tmpRetCode);
                    }
                    tmpRetAtsDetail.respCode = "0";

                    if (tmpIntRespCode >= 0) {
                        tmpRetAtsDetail.reqSeqID = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/TransNo");
                        tmpRetAtsDetail.respInfo = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/Info");
                        tmpRetAtsDetail.transState = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/State");
                        tmpRetAtsDetail.payInfoCode = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/InfoCode");
                        tmpRetAtsDetail.transAmt = tmpBkReader.getFirstText("/Root/RealTimeSingleTransQueryResp/Trans/Amount");
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        if (StringHelper.isNullOrEmpty(tmpRetMsg)) {
                            tmpRetAtsDetail.respInfo = "前置返回查询失败RespCode：" + tmpRetCode;
                        } else {
                            tmpRetAtsDetail.respInfo = tmpRetMsg;
                            if (tmpRetMsg.contains("处理中")) {
                                tmpRetAtsDetail.respCode = "0";
                                tmpRetAtsDetail.transState = "4";
                                tmpRetAtsDetail.payInfoCode = "I4001";
                            }
                        }
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }
}
